<template>
  <a-row gutter="16">
    <a-col :span="24">
      <a-card bordered title="连接配置">
        <template #extra>
          <a-button type="primary" ghost @click="save">保存全部配置</a-button>
        </template>
        <a-descriptions bordered size="small" style="width: 40%" :column="1">
          <a-descriptions-item label="从站模式">
            <a-select v-model:value="slaveConfig.slaveMode" :options="modeList" style="width: 100%;"></a-select>
          </a-descriptions-item>
          <a-descriptions-item label="串口名称" v-if="slaveConfig.slaveMode=='serial'">
            <a-input v-model:value="slaveConfig.slaveName"></a-input>
          </a-descriptions-item>
          <a-descriptions-item label="波特率" v-if="slaveConfig.slaveMode=='serial'">
            <a-input v-model:value="slaveConfig.slaveBaudRate"></a-input>
          </a-descriptions-item>
          <a-descriptions-item label="端口" v-if="slaveConfig.slaveMode=='network'">
            <a-input v-model:value="slaveConfig.slavePort"></a-input>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
    </a-col>
    <a-col :span="24">
      <a-card :bordered="false" title="">
        <template #extra>
          <a-flex align="center">
            模拟从站地址：
            <a-input-number v-model:value="rule.server"></a-input-number>
          </a-flex>
        </template>
        <a-card size="small" :bordered="false">
          <a-radio-group v-model:value="tab">
            <a-radio-button :value="item.value" v-for="item in rule.register">{{ item.name }}</a-radio-button>
          </a-radio-group>
          <a style="margin-left: 30px;color: red">注意：寄存器地址最大支持为【5000】</a>
        </a-card>
        <a-card size="small" :bordered="false">
          <a-button style="margin-bottom: 10px" type="primary" ghost @click="createClick">创建点位</a-button>
          <a-table :columns="columns" :data-source="rule.register.filter(l=>l.value==tab)[0].children">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'name'">
                <a-input v-if="record.tag=='new'" v-model:value="record.name"></a-input>
                <span v-else>{{ record.name }}</span>
              </template>
              <template v-if="column.dataIndex === 'address'">
                <a-input style="width: 100%;" v-if="record.tag=='new'"
                                v-model:value="record.address"></a-input>
                <span v-else>{{ record.address }}</span>
              </template>
              <template v-if="column.dataIndex === 'buildData'">
                <a-button type="link" @click="setRule(record)">规则配置</a-button>
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button danger type="link" @click="deleteLine(record)">删除</a-button>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-card>
    </a-col>
  </a-row>

  <a-modal v-model:open="isOpen" title="规则配置" ok-text="确认" cancel-text="取消" @ok="saveNewRule">
    <a-button type="primary" ghost @click="addRule" style="margin: 10px 0">增加</a-button>
    <!--    {{registerData}}-->
    <a-card size="small" title="数据源" style="margin-bottom: 10px" v-for="now in nowRule">
      <template #extra>
        <a-button danger type="link" @click="deleteRule(now)">删除</a-button>
      </template>
      <div style="margin: 5px 0px"> 从站：</div>
      <a-select style="width: 100%" v-model:value="now.server">
        <a-select-option v-for="(rd,rk,ei) in registerData" :value="rk" :key="rk">
          从站-{{ rk }}
        </a-select-option>
      </a-select>
      <div style="margin: 5px 0px"> 寄存器地址：</div>
      <a-select style="width: 100%" v-model:value="now.address">
        <a-select-option v-for="rd in registerData[now.server]" :value="rd.registerType+'-'+rd.address"
                         :key="rd.registerType+'-'+rd.address">
          {{ (rd.registerType == 'keep' ? '保持寄存器【03】' : '输入寄存器【04】') + '[' + rd.address + ']' + rd.name }}
        </a-select-option>
      </a-select>
      <div style="margin: 5px 0px"> 运算：</div>
      <a-select style="width: 100%" v-model:value="now.compute" allow-clear>
        <a-select-option value="+" key="+">+</a-select-option>
        <a-select-option value="-" key="-">-</a-select-option>
        <a-select-option value="*" key="*">*</a-select-option>
        <a-select-option value="/" key="/">/</a-select-option>
      </a-select>
    </a-card>
  </a-modal>
</template>
<script setup>

import {ref} from "vue";
import {baseRequest} from "@/utils/request.js";
import {message} from "ant-design-vue";
import {uuid} from "@/utils/common.js";

const isOpen = ref(false)
const registerData = ref()
baseRequest("/rule_value", {}).then(res => {
  registerData.value = res.data.data
})

const tab = ref('keep')

const activeKey = ref(null)
const nowRule = ref([])

const addRule = () => {
  nowRule.value.push({
    id: uuid(8, 16),
    server: null,
    address: null,
    compute: null
  })
}
const deleteRule = (record) => {
  nowRule.value = nowRule.value.filter(item => item.id !== record.id)
}

const saveNewRule = () => {
  rule.value.register.filter(l => l.value == tab.value)[0].children.filter(item => item.id == activeKey.value)[0].buildData = JSON.stringify(nowRule.value)
  isOpen.value = false
  activeKey.value = null
  nowRule.value = []
}
const columns = [
  {
    title: '测点名称',
    dataIndex: 'name',
  },
  {
    title: '寄存器地址',
    dataIndex: 'address',
  },
  {
    title: '数据类型',
    dataIndex: 'type',
  },
  {
    title: '构建数据',
    dataIndex: 'buildData',
  },
  {
    title: '操作',
    dataIndex: 'action',
  }

]
const rule = ref({
  server: 1,
  register: [
    {
      value: 'keep',
      name: '保持寄存器-[03]',
      children: []
    }
  ]
})

const createClick = () => {
  rule.value.register.filter(l => l.value == tab.value)[0].children.push({
    id: uuid(8, 16),
    tag: 'new',
    name: '测点名称',
    address: null,
    type: '单精度浮点',
    buildData: ''
  })
}

const deleteLine = (record) => {
  rule.value.register.filter(l => l.value == tab.value)[0].children = rule.value.register.filter(l => l.value == tab.value)[0].children.filter(item => item.id !== record.id)
}
const setRule = (record) => {
  isOpen.value = true
  activeKey.value = record.id;
  if (record.buildData) {
    nowRule.value = JSON.parse(record.buildData)
  } else {
    nowRule.value = []
  }
}

const modeList = ref([
  {
    label: "Modbus RTU",
    value: "serial",
  },
  {
    label: "Modbus TCP",
    value: "network",
  }
])
const slaveConfig = ref({})

baseRequest("/config/get/control", {}).then(res => {
  slaveConfig.value = res.data.data
  if (slaveConfig.value.slaveRule) {
    rule.value = JSON.parse(slaveConfig.value.slaveRule)
  }
})
const save = () => {
  slaveConfig.value.slaveRule = JSON.stringify(rule.value)
  baseRequest("/config/set/control", slaveConfig.value, 'post').then(res => {
    if (res.data.code == 200) {
      message.success("保存成功，重启服务后生效")
    } else {
      message.error(res.data.message)
    }
  })
}
</script>

<style scoped>

</style>
